package tw.zld369504.wol.utils;

import android.text.TextUtils;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Pattern;

public class PacketUtil {
    static {
        System.loadLibrary("ZWMagicPacket_1_0_0");
    }

    public native byte[] getWakeUpPacket(byte[] macData);

    public final DatagramPacket getConstructedPacket(byte[] macData, String address) {
        byte[] sendByte = getWakeUpPacket(macData);
        InetAddress serverAddress = null;
        try {
            serverAddress = InetAddress.getByName(address);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return new DatagramPacket(sendByte, sendByte.length, serverAddress, 4567);
    }

    public boolean checkIpValid(String ip) {
        if (!TextUtils.isEmpty(ip)) {
            // 定义正则表达式
            String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                    + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
            // 判断ip地址是否与正则表达式匹配
            return ip.matches(regex);
        } else {
            return false;
        }
    }

    public boolean checkMacAddressValid(String macAddress) {
        if (macAddress.length() != 17) {
            return false;
        }
        String patternMac = "^[a-fA-F0-9]{2}+:[a-fA-F0-9]{2}+:[a-fA-F0-9]{2}+:[a-fA-F0-9]{2}+:[a-fA-F0-9]{2}+:[a-fA-F0-9]{2}$";
        Pattern pa = Pattern.compile(patternMac);
        return pa.matcher(macAddress).find();
    }

    public byte[] macStr2Byte(String macStr) {
        return hexStr2Bytes(macStr.replaceAll(":", ""));
    }

    private static byte[] hexStr2Bytes(String src) throws NumberFormatException {
        int m, n;
        int l = src.length() / 2;
        byte[] ret = new byte[l];
        for (int i = 0; i < l; i++) {
            m = i * 2 + 1;
            n = m + 1;
            ret[i] = uniteBytes(src.substring(i * 2, m), src.substring(m, n));
        }
        return ret;
    }

    private static byte uniteBytes(String src0, String src1) throws NumberFormatException {
        byte b0 = (byte) (Byte.decode("0x" + src0).byteValue() << 4);
        byte b1 = Byte.decode("0x" + src1).byteValue();
        return (byte) (b0 | b1);
    }
}
